package com.hubu.queue;
import java.util.LinkedList;
public class MessageQueue <T>{
    private final int maxSize;
    private java.util.Queue<T>  taskQueue=new LinkedList<>();
    public MessageQueue(final int maxSize){
        this.maxSize=maxSize;
        taskQueue=new LinkedList<>();
    }
    public int size(){
        synchronized (taskQueue){
            return taskQueue.size();
        }
    }
    public void offer(T message){
        synchronized (taskQueue){
            while(taskQueue.size()==maxSize){
                try {
                    taskQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                taskQueue.offer(message);
                taskQueue.notifyAll();
            }
        }
    }
    public T take(){
       synchronized (taskQueue){
           while(taskQueue.isEmpty()){
               try {
                   taskQueue.wait();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
           T task = taskQueue.poll();
           taskQueue.notifyAll();
           return task;
       }
    }
}
